const {blog,Op} = require('../sequelize/sequelize')



fn_data=async(ctx)=>{
   
    await blog.findAll().then((res)=>{
        ctx.body=res
    })
}
fn_del=async(ctx)=>{
    let id = ctx.request.query.id
    await blog.findByPk(id).then( async(res)=>{
        await res.destroy()
    })

    await blog.findAll().then((res)=>{
        ctx.body=res
    })
}

fn_query=async(ctx)=>{
    let keyword = ctx.request.query.keyword
    console.log(keyword);
    if (keyword!=='') {
        
        if(isNaN(keyword)){
            await blog.findAll({
                where:{
                    [Op.or]:[
                        {title:keyword},
                        {digest:keyword},
                        {content:keyword},
                        {classify:keyword},
                        {author:keyword},
                        {time:keyword}
                    ]
                }
            }).then((res)=>{
                ctx.body=res
            })
        }else{
            await blog.findAll({
                where:{
                    [Op.or]:[
                        {id:keyword},
                        {title:keyword},
                        {digest:keyword},
                        {content:keyword},
                        {classify:keyword},
                        {author:keyword},
                        {time:keyword}
                    ]
                }
            }).then((res)=>{
                ctx.body=res
            })
        }

    }else{
        await blog.findAll().then((res)=>{
            ctx.body=res
        })
    }

}

fn_add =async(ctx)=>{

        let data = ctx.request.body

        await blog.create(data)

        await blog.findAll().then((res)=>{
            ctx.body=res
        })

}


fn_edit=async(ctx)=>{
    let data = ctx.request.body


    await blog.findByPk(data.id).then( async(res)=>{
            await res.update({
                title:data.title,
                digest:data.digest,
                content:data.content,
                classify:data.classify,
                author:data.author
            })
    })
    await blog.findAll().then((res)=>{
        ctx.body=res
    })
}

let get = [['/data',fn_data],['/query',fn_query],['/del',fn_del]]
let post=[['/add',fn_add],['/edit',fn_edit]]
module.exports={
    'GET':get,
    'POST':post
}